define(function(require){
    var main =require('/static/main.js');
    require('/static/ajaxfileupload.js');
    var m = new main();
    var sales = {
        AdvertorialId : $_GET['advertorialid'],
        islook:$_GET['islook'],
        adid :3,
        ImgSrc :'',
        chosetagList:[],
        tagList:[],
        _init:function(){
            // 初始化左边菜单
            this.bindEvent();
            this.cropperImg();
            this.simditor();
            this.datetime();
            this.ajaxUpload();
            this.getSignList();
            if(sales.AdvertorialId){
                this.getInitDataGet();
            }else{
                $(".q-cont-all").fadeIn();
            }
        },
        getInitDataGet:function(){
            $.ajax({
                type: "POST",
                url: "/promote/ad-template-get",
                data : {AdvertorialId:sales.AdvertorialId},
                dataType: "json",
                success: function (ret){
                    if(ret.IsBizSuccess){
                        if(ret.AdvertorialStatus == 100  || sales.islook){
                            $("#InputMessage").next().remove();
                            $("#InputMessage").remove();
                            $("#ShowMessage").removeClass("fl").find(".q-show-ret ").css("margin",'0 auto');

                        }
                        var data = ret.Model;
                        $("#ShowMessage .MainSrc").attr("src",data.MainSrc);
                        var Imgsrc =  data.MainSrc;
                        sales.ImgSrc = sales.GetUrlRelativePath(Imgsrc);
                        sales.setVal(data.Title,'Title');
                        sales.setVal(data.AdDescribe,'AdDescribe');
                        sales.setVal(data.ShopName,'ShopName');
                        sales.setVal(data.ShopAdd,'ShopAdd');
                        sales.setVal(data.ShopPhone,'ShopPhone');
                        $(".promote-style-call").attr("href",'tel:'+data.ShopPhone);
                        if(data.CountLimit){
                            $("#ShowMessage .CountLimit").html('<i class="">'+data.CountLimit+'</i>人');
                            $("#InputMessage .CountLimit").val(data.CountLimit);
                        }else{
                            $("#ShowMessage .CountLimit").html('不限');
                        }
                        sales.editor.setValue(data.Notice);
                        sales.setCont(data.AdContent);
                        //日期处理
                        $("#ActStartTime").val(m.formatTimeAll2(data.ActStartTime));
                        $("#ShowMessage .ActStartTime").html(m.formatLange2(new Date(m.substrTime(data.ActStartTime))));
                        $("#ApplyEndTime").val(m.formatTimeAll2(data.ApplyEndTime));
                        $("#ShowMessage .ApplyEndTime").html('报名截止：'+m.formatLange2(new Date(m.substrTime(data.ApplyEndTime)))).show();
                        $(".q-cont-all").fadeIn();
                        //tagList
                        if(ret.TagList.length > 0){
                            var tagstr = '';
                            $.each(ret.TagList,function(k,v){
                                tagstr+='<li class="chose_li"  data-id="'+v.TagId+'">'+v.TagName+'<span class="ion-close-round"></span></li>'
                            });
                            $(".tag-item").html(tagstr);
                            sales.chosetagList = ret.TagList;
                            sales.setTags();
                        }
                    }
                }
            });
        },
        getSignList:function(){
            $.ajax({
                type: "POST",
                url: "/customer/sign-list",
                dataType: "json",
                success: function (ret) {
                    var str = '';
                    if(ret.Models.length > 0){
                        $.each(ret.Models,function(k,v){
                            str+='<span class="Label_btnspan" data-id="'+v.TagId+'" data-name="'+v.TagName+'">'+v.TagName+'</span>'
                        });
                        sales.tagList = ret.Models;
                        sales.setTags();
                    }else{
                        $('.Label_btn').css({'text-align':'center'})
                        str+='暂无标签'
                    }
                    $('.Label_btn').html(str);
                }
            });

        },
        setTags:function(){
            if(sales.tagList.length > 0 && sales.chosetagList.length > 0){
                $.each(sales.tagList,function(k,v){
                    $.each(sales.chosetagList,function(key,val){
                        if(v.TagId == val.TagId){
                            $(".Label_btn").find(".Label_btnspan").eq(k).addClass("E8ECEE")
                        }
                    })
                })
            }
        },
        bindEvent:function(){
            //内容框输入
            $('.p-yl2').keyup(function (e) {
                var className = $(this).data("classname"); $("#ShowMessage ."+className).text($(this).val());
            });
            //手机号输入
            $('.ShopPhone').keyup(function (e) {
                $(".promote-style-call").attr("href",'tel:'+ $(this).val());
            });

            //价格
            $(document).on("change", ".p-yl4", function(){
                var reg = $(this).val().match(/\d+(\.\d{1,2})?/);
                var txt = '';
                if (reg != null)
                {
                    txt = reg[0];
                }
                $(this).val(txt);
                var className = $(this).data("classname");
                var pricetype = $(this).data("type");
                if(className == 'Price'){
                    var type =  $("input[name='admarkettype']:checked").val();
                    if(type == 200 && pricetype == 100){
                        return false;
                    }
                }
                if(txt.length && parseInt(txt)){
                    $("#ShowMessage ."+className).html('<i class="">'+txt+'</i>人');
                }else{

                    $("#ShowMessage ."+className).text('不限');
                }

            });

            //添加图片
            $(document).on("click", ".add-img", function(){
                var str  = sales.addStr('img');
                $(this).closest(".form-group").after(str[0]);
                var adid = $(this).attr("data-adid");
                $(".promote-cont"+adid).after(str[1]);
            });
            //添加文字说明
            $(document).on("click", ".add-font", function(){
                var str  = sales.addStr('font');
                $(this).closest(".form-group").after(str[0]);
                var adid = $(this).attr("data-adid");
                $(".promote-cont"+adid).after(str[1]);

            });
            //添加段落
            $(document).on("click", ".promote-addgrapeach ", function(){
                var str  = ' <div class="promote-grapeach">';
                var fontsrt = sales.addStr('font');
                var imgstr = sales.addStr('img');
                str  += fontsrt[0]+imgstr[0];
                str  += '</div>';
                $(".promote-scendcon").append(str);
                $(".promote-adcontent-item").append(fontsrt[1]+imgstr[1]);
            });
            //删除
            $(document).on("click", ".del-btn", function(){
                var adid = $(this).attr("data-adid");
                $(this).closest(".form-group").remove();
                $(".promote-cont"+adid).remove();
            });
            $(document).on("keyup", ".p-yl3", function(){
                var adid = $(this).attr("data-adid");
                $(".promote-cont"+adid).text($(this).val());
            });


            // 点击选择标签
            $(document).on('click','.Label_btn span',function(){
                if($(this).hasClass('E8ECEE')){
                    $(this).removeClass('E8ECEE')
                }else{
                    $(this).addClass('E8ECEE')
                }
            })
            //删除标签
            $(document).on('click','.chose_li',function(){
                var id = $(this).attr("data-id");
                $(".Label_btn").find(".Label_btnspan").each(function(){
                    var tagid = $(this).attr("data-id");
                    $(this).removeClass('E8ECEE');
                    if(parseInt(id) == parseInt(tagid)){
                        $(this).removeClass('E8ECEE');
                    }
                });
                $(this).remove();
            })
            // 选择完成
            $('.choseOk').click(function(){
                var str = '';
                $('.Label_btnspan.E8ECEE').each(function(k,v){
                    var id = $(this).data('id');
                    var name = $(this).data('name');
                    str +='<li class="chose_li"  data-id="'+id+'">'+name+'<span class="ion-close-round"></span></li>';
                })
                $(".tag-item").html(str);
                $('#TagList').modal('hide');
            });
            //保存
            $(document).on("click", ".SaveBtn", function(){
                sales.ActivitySave(false);
            });
            //发布
            $(document).on("click", ".PublishBtn", function(){
                sales.ActivitySave(true);
            });
        },
        isactive:false,
        ActivitySave:function(IsPublish){
            if(sales.isactive){
                return false;
            }
            var ImgSrc  = sales.ImgSrc.trim();
            var ImgArray = ImgSrc.substring(0,1);
            if(ImgArray == '/'){
                sales.ImgSrc =ImgSrc.substring(1);
            }
            var JsonData = {
                MainSrc : sales.ImgSrc ,
                Title :$("#InputMessage .Title").val().trim(),
                AdDescribe :$("#InputMessage .AdDescribe").val().trim(),
                ShopName :$("#InputMessage .ShopName").val().trim(),
                ShopAdd :$("#InputMessage .ShopAdd").val().trim(),
                ShopPhone :$("#InputMessage .ShopPhone").val().trim(),
                CountLimit :$("#InputMessage .CountLimit").val().trim(),
                ApplyEndTime :$("#InputMessage #ApplyEndTime").val().trim(),
                ActStartTime :$("#InputMessage #ActStartTime").val().trim(),
                Notice :sales.editor.getValue(),
                AdContent :sales.getCont()
            }
            var alltrue = true;
            var truearrya = [];

            truearrya.push(sales.errorMessage(JsonData.MainSrc,'mainsrc','请添加商品主图'));
            truearrya.push(sales.errorMessage(JsonData.Title,'title','请添加标题'));
            truearrya.push(sales.errorMessage(JsonData.AdDescribe,'addescribe','请添加商品名称'));
            //truearrya.push(sales.errorMessage(JsonData.ShopName,'shopname','请添加商户名称'));
            truearrya.push(sales.errorMessage(JsonData.ShopAdd,'shopadd','请添加商户地址'));
            truearrya.push(sales.errorMessage(JsonData.ShopPhone,'shopphone','请添加联系方式'));

            truearrya.push(sales.errorMessage(JsonData.ApplyEndTime,'applyendtime','请选择截止时间'));
            truearrya.push(sales.errorMessage(JsonData.ActStartTime,'actstarttime','请选择开始时间'));
            truearrya.push(sales.errorMessage(JsonData.Notice,'notice','请添加报名须知'));
            truearrya.push(sales.errorMessage(JsonData.AdContent,'adcontent','请添加详情说明'));
            $.each(truearrya,function(k,v){
               if(v == false){
                   alltrue = false;
                   return false;
               }
            });
            var tagList = [];
            $(".tag-item").find(".chose_li").each(function(){
                tagList.push($(this).attr("data-id"));
            });
            if(tagList.length > 0){
                JsonData.TagIds = tagList;
            }
            if(alltrue){
                JsonData.AdvertorialId = sales.AdvertorialId;
                sales.isactive = true;
                $.ajax({
                    type: "POST",
                    url: "/promote/ad-activity-create",
                    data :JsonData,
                    dataType: "json",
                    success: function (ret){
                        if(ret.IsBizSuccess){
                            if(IsPublish){
                                //发布
                                $.ajax({
                                    type: "POST",
                                    url: "/promote/ad-publish",
                                    data :{AdvertorialId:ret.AdvertorialId},
                                    dataType: "json",
                                    success: function (ret){
                                        sales.isactive = false;
                                        if(ret.IsBizSuccess){
                                            layer.msg("发布成功");
                                            setTimeout(function(){
                                                window.location.href = "/promote/mypromote";
                                            },1500);
                                        }else{
                                            layer.msg("发布失败");
                                        }
                                    }
                                });
                            }else{
                                sales.isactive = false;
                                layer.msg("保存成功");
                                setTimeout(function(){
                                    window.location.href = "/promote/mypromote";
                                },1500);
                            }
                        }else{
                            sales.isactive = false;
                            if(IsPublish){
                                layer.msg("发布失败");
                            }else{
                                layer.msg("保存失败");
                            }

                        }

                    }
                });
            }
        },
        setVal:function(data,classname){
            $("#ShowMessage ."+classname).text(data);
            $("#InputMessage ."+classname).val(data);
        },
        setCont:function(AdContent){
            $(".promote-adcontent-item").html(AdContent);
            var str = '<div class="promote-grapeach">';
            var i = 0;
            $(AdContent).each(function(){
                var classname = $(this).attr("class");
                classname = parseInt(classname.split("promote-cont")[1]);
                i = classname > i ?classname : i;
                if($(this).find("img").length){
                    var imgsrc = $(this).find("img").attr("src");
                    str += '<div class="form-group overflow">\
                <label class="col-md-2 control-label padleft17" style="font-weight: 500;">展示图片：</label>\
                <div class="col-md-7 promote-chosetupload">\
                        <div class="input-group">\
                            <input type="text" id="example-input2-group1" name="example-input2-group1" class="form-control fileupload"  data-adid="classname" readonly="" value="'+imgsrc+'">\
                                <span class="input-group-addon"><i class="fa ion-image"></i></span>\
                            </div>\
                        </div>\
                        <div class="col-md-3 add-promote-btnlist">\
                            <ul class="p-ul5 p-ul7">\
                                <li class="add-img"  data-adid="'+classname+'"><span class="ion-image"></span></li>\
                                <li class="add-font" data-adid="'+classname+'"><span class="fa fa-font" style="font-size: 23px;"></span></li>\
                                <li class="del-btn"  data-adid="'+classname+'"><span class="fa fa-trash-o"></span></li>\
                                <div class="clear"></div>\
                            </ul>\
                        </div>\
                    </div>';
                }else{
                    var html  = $(this).html();
                    str += '<div class="form-group overflow">\
                    <label class="col-md-2 control-label padleft17" style="font-weight: 500;">文字说明：</label>\
                    <div class="col-md-7">\
                        <textarea class="form-control p-yl3"  data-adid="' + classname + '">'+html+'</textarea>\
                    </div>\
                    <div class="col-md-3 add-promote-btnlist">\
                        <ul class="p-ul5 p-ul7">\
                            <li class="add-img" data-adid="' + classname + '"><span class="ion-image"></span></li>\
                            <li class="add-font" data-adid="' + classname + '"><span class="fa fa-font" style="font-size: 23px;"></span></li>\
                            <li class="del-btn"   data-adid="' + classname + '"><span class="fa fa-trash-o"></span></li>\
                            <div class="clear"></div>\
                        </ul>\
                    </div>\
                </div>';
                }
            });
            str  += '</div>';
            sales.adid = i+2;
            $(".promote-scendcon").html(str);

        },
        //剪切图片
        //剪切图片
        cropperImg:function(){
            var options =
            {
                imageBox: '.imageBox',
                thumbBox: '.thumbBox',
                spinner: '.spinner',
            }
            var cropper = '';
            document.querySelector('#MainSrc').addEventListener('change', function(){
                var MyTest = document.getElementById("#MainSrc");
                var _this = this;

                var reader = new FileReader();
                reader.onload = function(e) {
                    options.imgSrc = e.target.result;
                    var image = new Image();
                    image.src = e.target.result;
                    image.onload = function() {
                        if(image.width < 700 || image.height < 400){
                            layer.msg("图片尺寸必须大于700*400");
                            return false;
                        }else{
                            bytesupload(options.imgSrc);
                            return false;
                        }
                    };
                }
                reader.readAsDataURL(this.files[0]);
            })
            document.querySelector('#btnCrop').addEventListener('click', function(){
                var img = cropper.getDataURL();
                bytesupload(img);
            })

            var bytesupload = function(base){
                $.ajax({
                    type: "POST",
                    url: "/promote/get-bytes-by-image-path",
                    data : {baseImg:base},
                    dataType: "json",
                    success: function (ret){
                        if(ret.IsBizSuccess){
                            $(".MainSrc").attr("src",ret.ImgSrc);
                            $("#MainSrc").next(".input-group").find("input").val(ret.ImgSrc);
                            sales.ImgSrc = ret.FileName;
                            $("#CutImg").modal('hide');
                        }else{
                            layer.msg("图片上传失败，请重新上传！");
                        }
                    }
                });
            }
        },
        //上传图片
        ajaxUpload:function(){
            var adid = 0;
            var obj = '';
            $(document).on("click", ".fileupload", function(){
                $("#file").click();
                adid = $(this).attr("data-adid");
                obj = $(this);
            });
            //图片上传
            $("#file").on("change",function () {
                ajaxFileUpload();
            });
            function ajaxFileUpload(){
                $.ajaxFileUpload({
                    url:m.baseUrl+"/customer/edit-head",
                    secureuri: false,
                    fileElementId: 'file',
                    dataType: 'json',
                    success: function (ret) {
                        if(ret.IsBizSuccess){
                            obj.val(ret.Photo);
                            $(".promote-cont"+adid).find("img").attr('src',ret.Photo)
                        }else{
                            layer.msg(ret.ErrMsg);
                            return false;
                        }
                    }
                })
                return false;
            }
        },
        //日期
        datetime:function(){

            ////初始化日期控件
            //$('#ApplyEndTime').datetimepicker({
            //    format:'yyyy-mm-dd hh:ii',
            //    language:'zh-CN',
            //    autoclose: true,
            //    'startDate':new Date()
            //}).on("changeDate",function(ev){
            //    var str =  $("#ApplyEndTime").val();
            //    var newstr = str.split('-');
            //    var day = newstr[2].split(" ");
            //    var hout = day[1].split(":");
            //    var datestr = newstr[0]+'年' + newstr[1]+ '月' +day[0]+ '日 ' +day[1];
            //    $(".ApplyEndTime").html('报名截止：'+datestr).show();
            //});
            //
            ////初始化日期控件
            //$('#ActStartTime').datetimepicker({
            //    format:'yyyy-mm-dd hh:ii',
            //    language:'zh-CN',
            //    autoclose: true,
            //    'startDate':new Date()
            //}).on("changeDate",function(ev){
            //    var str =  $("#ActStartTime").val();
            //    var newstr = str.split('-');
            //    var day = newstr[2].split(" ");
            //    var hout = day[1].split(":");
            //    var datestr = newstr[0]+'年' + newstr[1]+ '月' +day[0]+ '日 ' +day[1];
            //    $(".ActStartTime").html('<span class="ion-ios7-clock"></span>'+datestr);
            //});




            //初始化日期控件
            function setEndTime(enddate){
                $('#ApplyEndTime').datetimepicker('remove');
                $('#ApplyEndTime').datetimepicker({
                    format:'yyyy-mm-dd hh:ii',
                    language:'zh-CN',
                    autoclose: true,
                    'startDate':new Date(),
                    'endDate':sales.transferDate(enddate)
                });
            }
            function transferTime(str){
                var newstr=str.replace(/-/g,'-');
                var newdate=new Date(newstr);
                var time=newdate.getTime();
                return time;
            }
            //结束时间戳和开始时间戳比较
            function checkTime(start,end){
                if(end <= start){
                    return true;
                }
                return false;
            }
            $('#ApplyEndTime').datetimepicker({
                format:'yyyy-mm-dd hh:ii',
                language:'zh-CN',
                autoclose: true,
                'startDate':new Date()
            }).on("changeDate",function(ev){
                var transferdate = sales.transferDate($("#ApplyEndTime").val());//转时间日期

                var str =  $("#ApplyEndTime").val();
                var newstr = str.split('-');
                var day = newstr[2].split(" ");
                var hout = day[1].split(":");
                var datestr = newstr[0]+'年' + newstr[1]+ '月' +day[0]+ '日 ' +day[1];
                $(".ApplyEndTime").html('报名截止：'+datestr).show();


                var newtime = new Date();
                $('#ActStartTime').datetimepicker('remove');
                $('#ActStartTime').datetimepicker({
                    format:'yyyy-mm-dd hh:ii',
                    language:'zh-CN',
                    autoclose:true,
                    'startDate':transferdate < newtime ? newtime :transferdate
                }).on("changeDate",function(ev){
                    var enddate=$("#ActStartTime").val();
                    var str=$("#ActStartTime").val();
                    var newstr = str.split('-');
                    var day = newstr[2].split(" ");
                    var hout = day[1].split(":");
                    var datestr = newstr[0]+'年' + newstr[1]+ '月' +day[0]+ '日 ' +day[1];
                    $(".ActStartTime").html('<span class="ion-ios7-clock"></span>'+datestr);
                    setEndTime(enddate);
                });
            });
            $('#ActStartTime').datetimepicker({
                format:'yyyy-mm-dd hh:ii',
                language:'zh-CN',
                'startDate':new Date(),
                autoclose:true
            }).on("changeDate",function(ev){
                var enddate=$("#ActStartTime").val();
                var str=$("#ActStartTime").val();
                var newstr = str.split('-');
                var day = newstr[2].split(" ");
                var hout = day[1].split(":");
                var datestr = newstr[0]+'年' + newstr[1]+ '月' +day[0]+ '日 ' +day[1];
                $(".ActStartTime").html('<span class="ion-ios7-clock"></span>'+datestr);

                setEndTime(enddate);
            });

        },
        //文本编辑器
        editor:'',
        simditor:function(){
            sales.editor = new Simditor({textarea:$("#editor"),toolbar:false});
            sales.editor.on('valuechanged',function(){
                $("#ShowMessage .Notice").html(sales.editor.getValue());
            });
        },
        getCont:function(){
            var adContent = '';
            $(".promote-scendcon").find(".col-md-7").each(function(k){
                var str  = '';
                if($(this).find("textarea").length){
                    var value  = $(this).find("textarea").val().trim();
                    if(value.length > 1){
                        str += '<p class="promote-cont'+k+'">'+value+'</p>';
                    }
                }else if($(this).find(".fileupload").length){
                    var value  = $(this).find(".fileupload").val().trim();
                    if(value.length > 1){
                        str += '<p class="promote-cont'+k+'"><img src="'+ value +'"></p>';
                    }
                }
                adContent += str;
            });
            return adContent;
        },
        //错误处理
        errorMessage:function(str,classname,errmsg){
            if(str.length < 1){
                var html = $(".pass-msg."+classname).html();
                if(html.length < 1){
                    $(".pass-msg."+classname).html(errmsg);
                }
                return false;
            }else{
                $(".pass-msg."+classname).html("");
                return true
            }
        },
        //添加段落
        addStr:function(addtype){
            if(addtype == 'img'){
                var str = '<div class="form-group overflow">\
                <label class="col-md-2 control-label padleft17" style="font-weight: 500;">展示图片：</label>\
                <div class="col-md-7 promote-chosetupload">\
                        <div class="input-group">\
                            <input type="text" id="example-input2-group1" name="example-input2-group1" class="form-control fileupload"  data-adid="'+sales.adid+'" readonly="">\
                                <span class="input-group-addon"><i class="fa ion-image"></i></span>\
                            </div>\
                        </div>\
                        <div class="col-md-3 add-promote-btnlist">\
                            <ul class="p-ul5 p-ul7">\
                                <li class="add-img"  data-adid="'+sales.adid+'"><span class="ion-image"></span></li>\
                                <li class="add-font" data-adid="'+sales.adid+'"><span class="fa fa-font" style="font-size: 23px;"></span></li>\
                                <li class="del-btn"  data-adid="'+sales.adid+'"><span class="fa fa-trash-o"></span></li>\
                                <div class="clear"></div>\
                            </ul>\
                        </div>\
                    </div>';
                var str1 = '<p class="promote-cont'+sales.adid+'"><img src="/modules/img/default.jpg"></p>';
            }else if(addtype == 'font') {
                var str = '<div class="form-group overflow">\
                    <label class="col-md-2 control-label padleft17" style="font-weight: 500;">文字说明：</label>\
                    <div class="col-md-7">\
                        <textarea class="form-control p-yl3"  data-adid="' + sales.adid + '"></textarea>\
                    </div>\
                    <div class="col-md-3 add-promote-btnlist">\
                        <ul class="p-ul5 p-ul7">\
                            <li class="add-img" data-adid="' + sales.adid + '"><span class="ion-image"></span></li>\
                            <li class="add-font" data-adid="' + sales.adid + '"><span class="fa fa-font" style="font-size: 23px;"></span></li>\
                            <li class="del-btn"   data-adid="' + sales.adid + '"><span class="fa fa-trash-o"></span></li>\
                            <div class="clear"></div>\
                        </ul>\
                    </div>\
                </div>';
                var str1 = '<p class="promote-cont'+sales.adid+'"></p>';
            }
            sales.adid ++;
            return [str,str1];

        },

        //将时间字符串转为date
        transferDate:function(data){
            var start_time = data;
            var newTime= start_time.replace(/-/g,"-");
            var transferdate = new Date(newTime);
            return transferdate;
        },
        //去除域名获取相对路径
        GetUrlRelativePath:function(url){
            var arrUrl = url.split("//");
            var length = arrUrl.length;
            if(length > 1){
                var start = arrUrl[length-1].indexOf("/");
                var relUrl = arrUrl[length-1].substring(start);//stop省略，截取从start开始到结尾的所有字符
                if(relUrl.indexOf("?") != -1){
                    relUrl = relUrl.split("?")[0];
                }
                return relUrl;
            }else{
                return url;
            }
        }
    }
    sales._init();

})